package com.itbour.dto.user;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.itbour.common.util.StringUtils;


/**
 * 获取oss文件列表方法
 * @author 李琦
 */
public class GetOssFileListUtil {

	public static String endpoint = "http://oss.aliyuncs.com";
	public static String accessKeyId = "gvmMBtVhdrkVYqAt";
	public static String accessKeySecret = "BgDhEvnYqU1N3bawYc91Pgahm99umO";
	public static String bucketName = "itbour-static";

	private static OSS client = null;

	static final String content = "Hello OSS";
	static final String keyPrefix = "MyObjectKey";

	static ObjectListing objectListing = null;
	static String nextMarker = null;
	static final int maxKeys = 30;
	static List<OSSObjectSummary> sums = null;

	// 获取默认文件夹列表
	public static List<OSSObjectSummary> getDefaultFile() {
		try {
			// use default parameter to list the files. By default up to 100 entries
			// could be listed.
			// 使用默认参数来列出文件。默认情况下，最多可以列出100个条目。
			System.out.println("Default paramters:");
			objectListing = client.listObjects(bucketName);
			sums = objectListing.getObjectSummaries();
			for (OSSObjectSummary s : sums) {
				System.out.println("\t" + s.getKey());
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
            client.shutdown();
        }
		return sums;
	}

	// 获取数量限制文件夹
	public static void getLimitFile() {
		try {
			// Sets the max keys with 200 (the max value could be 1000).
			System.out.println("With max keys:");
			objectListing = client.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(200));

			sums = objectListing.getObjectSummaries();
			for (OSSObjectSummary s : sums) {
				System.out.println("\t" + s.getKey());
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            client.shutdown();
        }
	}
	
	// 获取带有指定前缀的对象。默认情况下，它返回到100个条目。
	public static void getAppointPrefix(){
		try {
			// Gets the object with specified prefix. By default it returns up to 100 entries.
	        System.out.println("With prefix:"+keyPrefix);
	        objectListing = client.listObjects(new ListObjectsRequest(bucketName).withPrefix(keyPrefix));
	        
	        sums = objectListing.getObjectSummaries();
	        for (OSSObjectSummary s : sums) {
	            System.out.println("\t" + s.getKey());
	        }
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            client.shutdown();
        }
	}
	
	public static void addNewFile(String fileName){// 添加文件夹
		try {
			if (StringUtils.isNotEmpty(fileName)){
				client = new OSSClientBuilder().build(endpoint,accessKeyId, accessKeySecret);
				InputStream instream = new ByteArrayInputStream(new byte[0]);// 新建文件夹
				client.putObject(bucketName, fileName, instream);
				System.out.println("add fileName:"+fileName);
			} else {
				new Exception("the file name is null");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            client.shutdown();
        }
	}
	
	// 获取所有文件夹
	public static Map<String, Object> pageGetAllLimit(String nextMarker,String prefix){
		Map<String, Object> parm = new HashMap<String, Object>();
		try {
	        System.out.println("nextMarker:" +nextMarker);
	        objectListing = client.listObjects(new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(10));// 一页取10个文件夹
            sums = objectListing.getObjectSummaries();
            
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
            nextMarker = objectListing.getNextMarker();
            
            parm.put("sums",sums);
            parm.put("nextMarker",nextMarker);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            client.shutdown();
        }
		return parm;
	}
	
	// 指定 prefix
	public static ObjectListing pageGetAllByPrefix(String nextMarker,String prefix){
		try {
			client = new OSSClientBuilder().build(endpoint,accessKeyId, accessKeySecret);
            objectListing = client.listObjects(new ListObjectsRequest(bucketName).withPrefix(prefix).withMarker(nextMarker).withMaxKeys(100).withDelimiter("/"));
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            client.shutdown();
        }
		return objectListing;
	}
	
	
	
	// 删除指定文件
	public static void delAppointPrefix(String key){
		try {
			if (StringUtils.isNotEmpty(key)){
				List<String> keys = new ArrayList<String>();
				keys.add(key);
				client = new OSSClientBuilder().build(endpoint,accessKeyId, accessKeySecret);
				client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
			} else {
				new Exception("del file is not permit null");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            client.shutdown();
        }
	}
	
	public static void uploadFile(String prefix,InputStream inputStream) throws FileNotFoundException{
		try {
			client = new OSSClientBuilder().build(endpoint,accessKeyId, accessKeySecret);
			client.putObject(bucketName, prefix, inputStream);
			// 关闭OSSClient。
			client.shutdown();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            client.shutdown();
        }
	}
	
	
	
	@SuppressWarnings("null")
	public static OutputStream downFile(){
		OutputStream outputStream = null;
		try {
			// 创建OSSClient实例。
			client = new OSSClientBuilder().build(endpoint,accessKeyId, accessKeySecret);
			// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
			OSSObject ossObject = client.getObject(bucketName, "liqi.txt");
			// 读取文件内容。
			System.out.println("Object content:");
			// 读取文件内容。
			InputStream input = ossObject.getObjectContent();
			
			int byteCount = 0;
            //1M逐个读取
            byte[] bytes = new byte[1024*1024];
            while ((byteCount = input.read(bytes)) != -1){
                outputStream.write(bytes, 0, byteCount);
            }

            input.close();
            outputStream.close();
			client.shutdown();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
            client.shutdown();
        }
		return outputStream;
	}

}
